package com.example.event_resource_java.commons.util.easyexcel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.example.event_resource_java.commons.vo.ExcelStudentVO;
import com.google.common.collect.Lists;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.regex.Pattern;

/*
 *  @author : JingChangTian
 *  @date   : 2024/3/18 10:18
 *  @description :
 *
 */
public class CustomerDailyImportListener extends AnalysisEventListener {

    List mobileList = Lists.newArrayList();

    /**
     * 每解析一行，回调该方法
     * @param data
     * @param context
     */
    @Override
    public void invoke(Object data, AnalysisContext context) {
        // 需要解析的字段
        String mobile = ((ExcelStudentVO) data).getMobile();
        if (StringUtils.isEmpty(mobile) || !Pattern.matches("^1[3-9]\\d{9}$", mobile)) {
            throw new RuntimeException(String.format(((ExcelStudentVO) data).getName() + "手机号错误!", context.readRowHolder().getRowIndex()));
        }
        if (mobileList.contains(mobileList)) {
            throw new RuntimeException(String.format(((ExcelStudentVO) data).getName() + "手机号重复!", context.readRowHolder().getRowIndex()));
        } else {
            mobileList.add(mobile);
        }


    }

    /**
     * 出现异常回调
     * @param exception
     * @param context
     * @throws Exception
     */
    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        // ExcelDataConvertException:当数据转换异常的时候，会抛出该异常，此处可以得知第几行，第几列的数据
        if (exception instanceof ExcelDataConvertException) {
            Integer columnIndex = ((ExcelDataConvertException) exception).getColumnIndex() + 1;
            Integer rowIndex = ((ExcelDataConvertException) exception).getRowIndex() + 1;
            String message = "第" + rowIndex + "行，第" + columnIndex + "列" + "数据格式有误，请核实";
            throw new RuntimeException(message);
        } else if (exception instanceof RuntimeException) {
            throw exception;
        } else {
            super.onException(exception, context);
        }
    }

    /**
     * 解析完全部回调
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        mobileList.clear();
    }
}
